$(document).ready(function() {
    SB.ArticleModel = Backbone.Model.extend();

    SB.ArticleCollection = Backbone.Collection.extend({
        model : SB.ArticleModel
    });

    SB.articleCollection = new SB.ArticleCollection();
    SB.articleCollection.reset(SB.articles);
    SB.ArticleModel = Backbone.Model.extend();

    SB.popoverArticleId = null;

    SB.ArticleDetailView = Backbone.View.extend({
        template : _.template($('#article-detail-tpl').html()),

        events : {
            "click #comment-submit-btn" : "submitComment"
        },

        render : function() {
            $(this.el).html(this.template(this.model.toJSON()));
            SB.commentCollectionView = VM.createView("commentCollectionView", function() {
                return new SB.CommentCollectionView({
                    collection : SB.commentCollection,
                });
            });
            this.$('.article-detail-comments').html(SB.commentCollectionView.render().el);

            // For test only
            var url = "/api/comment/url/?url=" + encodeURIComponent(this.model.get('url'));
            $.get(url, function(data) {
                data = JSON.parse(data);
                console.log(data);
                SB.commentCollection.reset(data);
                console.log(SB.commentCollection);
            });
            return this;
        },

        submitComment : function() {
            var $this = this;
            var params = {};
            params.content = this.$('#comment-textarea').val();
            params.url = this.model.get('url');
            $.post('/api/comment/create/', params, function(data) {
                data = JSON.parse(data);
                $this.$('#comment-textarea').val('');
                var comment = new SB.Comment();
                comment.set(data);
                console.log(comment);
                SB.commentCollection.add(comment);

                // Update comments for article
                var statComments = $this.model.get('comments');
                $this.model.set({
                    "comments" : statComments + 1
                });
            });
        }
    });

    SB.ArticleView = Backbone.View.extend({
        events : {
            'click .bookmark' : "showPopover",
            'click .bookmark-active' : 'showPopover',
            'click .voteup' : "voteUp",
            'click .votedown' : "voteDown",
            'click .article-img' : 'showGallery',
            'click .article-title a' : "showArticleDetail",
            'click .comment' : "showArticleDetail"
        },

        initialize : function() {
            _.bindAll(this, 'render', 'resetVote')
            // Resize the images
            this.$('.article-img').imagesLoaded(function($images, $proper, $broken) {
                if ($proper.height() < $proper.parent().height()) {
                    $proper.css('width', 'auto');
                    $proper.css('height', '100%');
                }
            });
            this.model.on('change', this.update, this);

            // Show bookmark
            var id = this.model.get('id');
            console.log("article id" + id);
            if (SB.bookmarkArticles.get(id)) {
                this.$('.bookmark-active').slideDown();
            }
        },

        render : function() {
            return this;
        },

        showPopover : function(e) {
            console.log('showPopover');
            SB.popoverArticleId = this.model.get('id');
            this.$('.bookmark-active').slideDown();
            // popover demo
            this.$('a[rel=popover]').popover('show');
            e.stopPropagation();
        },

        update : function() {
            this.$('#stat-vote-up').text(this.model.get('vote_up'));
            this.$('#stat-vote-down').text(this.model.get('vote_down'));
            this.$('#stat-comments').text(this.model.get('comments'));
        },

        resetVote : function(data) {
            console.log(data);
            data = JSON.parse(data);
            this.model.set({
                "vote_up" : data.vote_up,
                "vote_down" : data.vote_down
            });
        },

        voteUp : function() {
            console.log('voteup');
            var payload = {};
            payload.article_id = this.model.get('id');
            payload.up = true;
            // Post
            $.post('/api/vote/create/', payload, this.resetVote);

        },

        voteDown : function() {
            console.log('votedown');
            var payload = {};
            payload.article_id = this.model.get('id');
            payload.up = false;
            // Post
            $.post('/api/vote/create/', payload, this.resetVote);
        },

        showGallery : function() {
            console.log("showGallery");
            $.fancybox.open(this.model.get('photos'), {
                prevEffect : 'fade',
                nextEffect : 'fade',
                helpers : {
                    title : {
                        type : 'outside'
                    },
                    thumbs : {
                        width : 60,
                        height : 60
                    }
                }
            });
        },

        showArticleDetail : function(e) {
            e.preventDefault();
            e.stopPropagation();
            var $this = this;
            SB.articleDetailView = VM.createView("articleDetailView", function() {
                return new SB.ArticleDetailView({
                    model : $this.model
                });
            });
            $.fancybox(SB.articleDetailView.render().el);
        }
    });

    SB.ArticleCollectionView = Backbone.View.extend({
        initialize : function() {
            _.bindAll(this, 'render');
            SB.articleCollection.on('add', this.addArticle);
        },

        render : function() {
            for (var i = 0; i < SB.articleCollection.length; i++) {
                (function(i) {
                    var view = new SB.ArticleView({
                        el : "#article-" + SB.articleCollection.at(i).get('id'),
                        model : SB.articleCollection.at(i)
                    });
                })(i);
            }
        },

        addArticle : function(article) {
            console.log(article);
            var view = new SB.ArticleView({
                el : "#article-" + article.get('id'),
                model : article
            });
        }
    });

    SB.AddNoteView = Backbone.View.extend({
        template : _.template($('#add-to-board-tpl').html()),

        events : {
            'click #create-note' : 'createNote'
        },

        initialize : function() {
            console.log("new popover");
            _.bindAll(this, 'render');
        },

        render : function() {
            $(this.el).html(this.template());
            return this;
        },

        createNote : function() {
            console.log("create note");
            var payload = {};
            payload.article_id = SB.popoverArticleId;
            console.log('article_id' + payload.article_id);
            payload.note = this.$('#note').val();
            payload.board_id = this.$('#board-id').val();
            $.post('/api/board/add-note/', payload, function(data) {
                console.log(data);
            });
            this.$('#note').val("");
            $("a[rel=popover]").popover('hide');
        }
    });
});
